<!--
 * @Author: Bing
 * @Date: 2024-02-06 00:31:33
 * @LastEditors: Bing
 * @LastEditTime: 2024-02-11 12:35:56
 * @Description: eid设置页面
 * @FilePath: \mi365plus\src\pages\eidSetting\eidSetting.vue
-->
<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useEidSaveStore, useMemberStore } from '@/stores';
// 表格数据
const data = () => {
  // 定义表格数据
  const userName = ref();
  const password = ref();
  const rows = ref<string[][]>(
    Array.from({ length: 8 }, () => Array.from({ length: 13 }, () => '')),
  );
  // 初始化表头
  const heard = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];
  for (let i = 0; i < heard.length; i++) {
    rows.value[0][i + 1] = heard[i];
  }
  rows.value[0][0] = '/';
  // 初始化第一列
  const row = ['1', '2', '3', '4', '5', '6', '7'];
  for (let i = 0; i < row.length; i++) {
    rows.value[i + 1][0] = row[i];
  }
  return {
    userName,
    password,
    rows,
  };
};
const { userName, password, rows } = data();
// 校验密码
const checkPassword = async (username: string, pass: string) => {
  uni.showLoading({ title: '正在校验账号密码...', mask: true });
  const { extractedString, pfProdValue } = await getCaptcha();
  const cookie = { 'PF-PROD': pfProdValue };
  try {
    // 请求url
    const res = await uni.request({
      url: `https://extranetcloud.marriott.com/userauth/idp/${extractedString}/resumeSAML20/idp/SSO.ping?pf.username=${username}&pf.pass=${pass}`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        Cookie: `${Object.entries(cookie)
          .map(([key, value]) => `${key}=${value}`)
          .join(';')}`,
      },
    });
    if (checkPass(res.data.toString()) === '登录成功') {
      console.log('登录成功');
      return true;
    } else {
      return false;
    }
  } catch (error) {
    return false;
  } finally {
    uni.hideLoading();
  }
};
// 获取验证码
const getCaptcha = async () => {
  const res = await uni.request({
    url: 'https://extranetcloud.marriott.com/2FAmarrsso/idp/eyJ2c2lkIjoidXJuOm1nc2Nsb3VkLm1hcnJpb3R0LmNvbSJ9/SSO.saml2?SAMLRequest=PHNhbWxwOkF1dGhuUmVxdWVzdCB4bWxuczpzYW1scD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnByb3RvY29sIiB4bWxuczpzYW1sPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBJRD0iXzdENTU2RDIyRjY1REE3QTcyNDlCQUMxMDc4RjEzOTM1IiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAyNC0wMi0xNFQxNDoyNzo0OVoiIERlc3RpbmF0aW9uPSJodHRwczovL2V4dHJhbmV0Lm1hcnJpb3R0LmNvbS8yRkFtYXJyc3NvL2lkcC9leUoyYzJsa0lqb2lkWEp1T20xbmMyTnNiM1ZrTG0xaGNuSnBiM1IwTG1OdmJTSjkvU1NPLnNhbWwyIiBDb25zZW50PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6Y29uc2VudDpjdXJyZW50LWltcGxpY2l0IiBGb3JjZUF1dGhuPSJmYWxzZSIgSXNQYXNzaXZlPSJmYWxzZSIgQXNzZXJ0aW9uQ29uc3VtZXJTZXJ2aWNlVVJMPSJodHRwczovL21nc2Nsb3VkLm1hcnJpb3R0LmNvbS9tZWxsb24vcG9zdFJlc3BvbnNlIj48c2FtbDpJc3N1ZXI%2BdXJuOm1nc2Nsb3VkLm1hcnJpb3R0LmNvbTwvc2FtbDpJc3N1ZXI%2BPHNhbWxwOk5hbWVJRFBvbGljeSBGb3JtYXQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpuYW1laWQtZm9ybWF0OnRyYW5zaWVudCIgQWxsb3dDcmVhdGU9InRydWUiLz48L3NhbWxwOkF1dGhuUmVxdWVzdD4%3D',
    method: 'POST',
    header: {
      'Content-Type': 'application/json',
    },
  });
  const scriptText = res.data.toString();
  // 创建一个正则表达式来匹配 PingbaseURL 变量的赋值部分
  const regex =
    /var PingbaseURL = PingURL\.concat\("\/idp\/(\w+)\/resumeSAML20\/idp\/SSO\.ping"\);/;

  // 使用正则表达式的 exec 方法进行匹配
  const match = regex.exec(scriptText);
  // 获取响应头中的 Set-Cookie
  var cookies = res.header['Set-Cookie'];

  // 解析出 PF-PROD Cookie 的值
  let pfProdValue = null;
  if (cookies) {
    // 将 Set-Cookie 拆分成单个 Cookie
    let cookieArray = cookies.split(';');

    // 遍历每个 Cookie，寻找 PF-PROD Cookie
    for (let i = 0; i < cookieArray.length; i++) {
      let cookie = cookieArray[i].trim();
      if (cookie.startsWith('PF-PROD=')) {
        // 提取 PF-PROD Cookie 的值
        pfProdValue = cookie.substring('PF-PROD='.length);
        break;
      }
    }
  }
  if (match) {
    const extractedString = match[1]; // 获取匹配到的第一个捕获组
    return { extractedString, pfProdValue };
  } else {
    return { extractedString: null, pfProdValue: null };
  }
};
// 判断密码是否正确
const checkPass = (htmlContent: string) => {
  // 使用正则表达式提取文本
  const match: RegExpMatchArray | null = htmlContent.match(
    /Authentication failed\.(.*?)\./,
  );

  if (match && match[1]) {
    const errorMessage: string = match[1].trim();
    console.log('提取到的错误消息:', errorMessage);
    return '登录失败';
  }
  // 使用正则表达式提取标题文本
  const matchTitle: RegExpMatchArray | null = htmlContent.match(
    /<title>(.*?)<\/title>/,
  );
  if (matchTitle && matchTitle[1]) {
    const title: string = matchTitle[1].trim();
    console.log('提取到的标题:', title);
    return '登录成功';
  }
};
// 保存按钮H5
// #ifdef H5
const save = async () => {
  // 判断数据不为空
  if (!userName.value || !password.value) {
    if (!userName.value) {
      uni.showToast({ title: '请输入EID账号', icon: 'error' });
    } else if (!password.value) {
      uni.showToast({ title: '请输入EID密码', icon: 'error' });
    }
    return;
  }
  // 保存数据
  useEidSaveStore().setEidSave({
    userName: userName.value,
    password: password.value,
    rows: rows.value,
  });
  uni.showToast({ title: '修改成功', icon: 'success' });
  // 退出登录
  useMemberStore().clearProfile();
  // 跳转到我的设置页面
  setTimeout(() => {
    uni.switchTab({ url: '/pages/mySetting/mySetting' });
  }, 500);
};
// #endif
// 保存按钮小程序
// #ifndef H5
const save = async () => {
  // 判断数据不为空
  if (!userName.value || !password.value) {
    if (!userName.value) {
      uni.showToast({ title: '请输入EID账号', icon: 'error' });
    } else if (!password.value) {
      uni.showToast({ title: '请输入EID密码', icon: 'error' });
    }
    return;
  }
  // 校验密码
  const isPass = await checkPassword(userName.value, password.value);
  // 判断密码是否正确
  if (isPass) {
    // 保存数据
    useEidSaveStore().setEidSave({
      userName: userName.value,
      password: password.value,
      rows: rows.value,
    });
    uni.showToast({ title: '修改成功', icon: 'success' });
    // 退出登录
    useMemberStore().clearProfile();
    // 跳转到我的设置页面
    setTimeout(() => {
      uni.switchTab({ url: '/pages/mySetting/mySetting' });
    }, 500);
  } else {
    uni.showToast({ title: 'EID密码错误', icon: 'error' });
    return;
  }
};
// #endif
const buttonName = ref('保存');
onLoad(() => {
  // 获取保存的表格数据
  const eidSaveData = useEidSaveStore().getEidSave();
  if (eidSaveData) {
    userName.value = eidSaveData.userName;
    password.value = eidSaveData.password;
    rows.value = eidSaveData.rows;
  }
});
</script>

<template>
  <uni-forms ref="form" label-position="top">
    <uni-card title="EID">
      <uni-forms-item label="EID账号" name="userName">
        <uni-easyinput
          type="text"
          v-model="userName"
          placeholder="请输入EID账号"
        />
      </uni-forms-item>
      <uni-forms-item label="EID密码" name="password">
        <uni-easyinput
          type="password"
          v-model="password"
          placeholder="请输入EID密码"
        />
      </uni-forms-item>
    </uni-card>
    <uni-card v-show="false">
      <uni-collapse>
        <uni-collapse-item :show-animation="true" title="矩阵图">
          <view class="table">
            <!-- 表格内容 -->
            <view class="row" v-for="(row, rowIndex) in rows" :key="rowIndex">
              <view
                class="cell"
                v-for="(cell, cellIndex) in row"
                :key="cellIndex"
              >
                <input
                  class="input"
                  type="text"
                  :disabled="rowIndex === 0 || cellIndex === 0"
                  v-model="rows[rowIndex][cellIndex]"
                />
              </view>
            </view>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </uni-card>
    <button class="bt" size="default" type="primary" @tap="save">
      {{ buttonName }}
    </button>
  </uni-forms>
</template>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-direction: column;

  .row {
    display: flex;

    .cell {
      flex: 1;
      border: 1px solid #ccc;
      padding: 5px;

      .input {
        width: 100%;
        border: none;
        outline: none;
      }
    }
  }
}

.bt {
  width: 60%;
  border-radius: 30px;
  background-color: #5199ff;
}
</style>
